package com.presto.directo.utils

import com.presto.directo.net.*
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitUtil {
    private lateinit var retrofit: Retrofit

    fun getInstance(baseUrl: String): Retrofit {
        if (!this::retrofit.isInitialized) {
            synchronized(RetrofitUtil::class.java) {
                if (!this::retrofit.isInitialized) {
                    val okHttpClient = OkHttpClient.Builder()
                        .dispatcher(Dispatcher().apply { maxRequestsPerHost = 10 })
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .build()
                    retrofit = Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create(GsonUtil.getInstance()))
                        .client(okHttpClient)
                        .build()
                }
            }
        }
        return retrofit
    }

}

fun getApiService(): ApiService {
    return RetrofitUtil.getInstance(ApiService.BaseUrl).create(ApiService::class.java)
}

fun getThirdApiService(): ThirdApiService {
    return RetrofitMap.getRetrofit("https://mex-api.advance.ai/").create(ThirdApiService::class.java)
}